#include "notification.h"
#include <QtCore/QTimer>
#include <QtCore/QSettings>

namespace acidone
{

NotificationManager::NotificationManager(Database *database, QObject *parent)
	:QObject(parent)
	,m_database(database)
	,m_dirtyDatabase(true)
{
	QSettings settings;
	m_lastCheckTime = settings.value("notification/lastcheck", QDateTime::currentDateTime().addYears(-1)).toDateTime();

	reloadTasks();

	connect(m_database, SIGNAL(changed()), this, SLOT(databaseChanged()));

	QTimer* timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(reloadTasks()));
	connect(timer, SIGNAL(timeout()), this, SLOT(checkTasks()));
	timer->setInterval(60*1000);
	timer->start();

	QTimer::singleShot(5*1000, this, SLOT(checkTasks()));
}

NotificationManager::~NotificationManager()
{
	QSettings settings;
	settings.setValue("notification/lastcheck", m_lastCheckTime);
}

void NotificationManager::databaseChanged()
{
	m_dirtyDatabase = true;
}

struct NotStartedTaskPred
{
	NotStartedTaskPred(const QDateTime& dateTime)
		:m_dateTime(dateTime)
	{
	}

	bool operator()(const Task& task) const
	{
		return !task.beginDateTime().isNull() &&
				task.beginDateTime().toLocalTime() > m_dateTime;
	}

	QDateTime m_dateTime;
};

void NotificationManager::reloadTasks()
{
	if (m_dirtyDatabase)
	{
		m_watchedTasks = m_database->tasksByCondition(NotStartedTaskPred(m_lastCheckTime));
		m_dirtyDatabase = false;
	}
}

void NotificationManager::checkTasks()
{
	Database::TaskList startedTasks;

	foreach(Task* task, m_watchedTasks)
	{
		if (task->isStarted())
		{
			startedTasks.append(task);
		}
	}

	if (!startedTasks.empty())
	{
		emit tasksStarted(startedTasks);

		foreach(Task* task, startedTasks)
		{
			m_watchedTasks.removeOne(task);
		}
	}

	m_lastCheckTime = QDateTime::currentDateTime();
}

}
